/*
 * BSP.c
 *
 *  Created on: 2025年10月18日
 *      Author: feng
 */
#include "esp_log.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/temperature_sensor.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "string.h"
#include "driver/gpio.h"

#include "BSP.h"
#include "Sensor.h"
#include "Display.h"





 
 
/*	默认modbus rtu slave参数	*/
ModbusRtuSlaveParameter DefaultModbusRtuSlaveParam = 
{
	.Parity = 0,								//MODBUS串口校验位：无
	.Baudrate = 19200,							//MODBUS串口波特率：19200
	.StopBits = 1,								//MODBUS串口停止位：1
	.TxdDelay = 20,								//MODBUS串口数据延时发送时间，单位：ms
	.T35Time = 0,								//MODBUS t35时间，超过这个值，则判断为一帧数据接收完成，单位：ms。
												//0--数据无效，由程序自动计算时间。
												//其他数值--有效
};



/*	默认工作模式配置信息	*/
WorkParameter DefaultWorkParam = 
{
	.WorkMode = WirelessSlave,							//ATPS工作模式：RS485通讯
	.NetId = 50,								//无线网络ID
	.NetChannel = 11,							//无线网络通道号
	.DeviceType = AtpsRa,						//设备类型：AtpsOa
	.SensorType = SHT41,						//传感器类型：SHT30
};


/*	默认应用配置信息	*/
AppParameter DefaultAppParam = 
{
	.ResetCount = 0,							//系统复位重启次数
	
	.AtpsSaTempCali = 0,						//送风温度校准，单位：℃
	.AtpsSaRhCali = 0,							//送风相对湿度校准，单位：%
	
	.AtpsOaTempCali = 0,						//新风温度校准，单位：℃
	.AtpsOaRhCali = 0,							//新风相对湿度校准，单位：%
	
	.AtpsMaTempCali = 0,                  		//混风温度校准，单位：℃
  	.AtpsMaRhCali = 0,                    		//混风相对湿度校准，单位：% 
  
    .AtpsExaTempCali= 0,                  		//排风温度校准，单位：℃
    .AtpsExaRhCali = 0,                   		//排风相对湿度校准，单位：% 
  
    .AtpsRoomaTempCali= 0,                		//室内温度校准，单位：℃
    .AtpsRoomaRhCali = 0,                 		//室内相对湿度校准，单位：% 
  
    .AtpsCoolaTempCali = 0,               		//表冷后温度校准，单位：℃
    .AtpsCoolaRhCali = 0,                 		//表冷后相对湿度校准，单位：% 
  
    .AtpsHeataTempCali = 0,               		//加热后温度校准，单位：℃
    .AtpsHeataRhCali = 0,                 		//加热后相对湿度校准，单位：% 
  
    .AtpsHumaTempCali = 0,                		//加湿后温度校准，单位：℃
    .AtpsHumaRhCali = 0,                  		//加湿后相对湿度校准，单位：% 
  
    .AtpsPreTempCali = 0,                 		//预处理后温度校准，单位：℃
    .AtpsPreRhCali = 0,                   		//预处理后相对湿度校准，单位：% 
  
    .AtpsRotTempCali = 0,                 		//转轮后温度校准，单位：℃
    .AtpsRotRhCali = 0,                   		//转轮后相对湿度校准，单位：% 
	
	.Atmosphere = 101.325,                		//大气压值，单位：KPa
	
	.SamplingPeriod = 1000,						//传感器数据采样时间间隔: 1000ms
	.AverageWindowSize = 5,						//移动平均窗口大小
};




/*	系统参数	*/
SystemParameter SysParam = { 0 };
/*	系统状态	*/
SystemState SysState  = { 0 };


static uint8_t DataBuffer[2048] = { 0 };


static temperature_sensor_handle_t chip_temp_sensor = NULL;


const char *TAG = "ATPS";



extern EventGroupHandle_t SysEvent;				//系统事件







/**
	* @brief  计算校验值
	* @param  value：需要校验的数据
	* @param  len：数据长度
	* @retval 返回校验值
  */
static uint8_t SysCheckvalue( uint8_t *value, uint16_t len )
{
	uint8_t sum = 0;
	uint16_t i;

	for( i=0; i<len; i++ )
	{
		sum = sum + value[i];
	}
	
	sum ^= 0xa5;
	return sum;
}



/**
	* @brief  往NVS写入数据
	* @param  key     Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty.
	* @param  value   The value to set.
	* @param  length  length of binary value to set, in bytes
	* @retval 	- ESP_OK if value was set successfully
    *           - ESP_FAIL if there is an internal error; most likely due to corrupted
  */
static esp_err_t NVS_WriteData( const char* key, const void* value, size_t length )
{
	esp_err_t err;
	nvs_handle_t NvsHandle;
	
	err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &NvsHandle);
    if (err != ESP_OK)
    {
		ESP_LOGE(TAG, "NVS open err!!!\r\n" );
		return err;
	} 
    
    err = nvs_set_blob(NvsHandle, key, value, length);
	if (err != ESP_OK)
	{
		ESP_LOGE(TAG, "NVS set blob err!!!\r\n" );
		return err;
	} 
	
	err = nvs_commit(NvsHandle);
    if (err != ESP_OK) 
    {
		
		ESP_LOGE(TAG, "NVS commit err!!!\r\n" );
		return err;
	}
	
	nvs_close(NvsHandle);
    return ESP_OK;
}



/**
	* @brief  从NVS读取数据
	* @param  key     Key name. Maximum length is (NVS_KEY_NAME_MAX_SIZE-1) characters. Shouldn't be empty.
	* @param  value   Pointer to the output value.
	* @param  length   The size of  output value.
	* @retval 	- ESP_OK if value was set successfully
    *           - ESP_FAIL if there is an internal error; most likely due to corrupted
  */
static esp_err_t NVS_ReadData( const char* key, void* out_value, size_t length )
{
	esp_err_t err;
	nvs_handle_t NvsHandle;
	size_t len = length;
	
	err = nvs_open(STORAGE_NAMESPACE, NVS_READWRITE, &NvsHandle);
    if (err != ESP_OK)
    {
		ESP_LOGE(TAG, "NVS open err!!!\r\n" );
		return err;
	} 
    
    err = nvs_get_blob(NvsHandle, key, out_value, &len);
	if (err != ESP_OK ) 
	{
		ESP_LOGE(TAG, "NVS get blob err!!!\r\n" );
		return err;
	}
	
	nvs_close(NvsHandle);
	
    return ESP_OK;
}



/**
  * @brief  恢复出厂设置
  * @param  none
  * @retval none
  */
static void FactoryReset( void )
{
   /*	MODBUS RTU从机配置信息恢复出厂值	*/
   {
		DefaultModbusRtuSlaveParam.Sum = SysCheckvalue( (uint8_t *)&DefaultModbusRtuSlaveParam, (sizeof(ModbusRtuSlaveParameter) - 1) );
		memcpy( DataBuffer, &DefaultModbusRtuSlaveParam, sizeof(ModbusRtuSlaveParameter) );
    	memcpy( &SysParam.ModbusRtuSlaveParam, &DefaultModbusRtuSlaveParam, sizeof(ModbusRtuSlaveParameter) );
    	
    
    	if( NVS_WriteData( NVS_ModbusRtuSlaveParam, DataBuffer, sizeof(ModbusRtuSlaveParameter) ) != ESP_OK )
	    {
	      SysState.NVS_Fault = Fault;
	    }
    	else SysState.NVS_Fault = NoFault;
    }
    
    
   /*	工作模式配置信息恢复出厂值	*/
   {
		DefaultWorkParam.Sum = SysCheckvalue( (uint8_t *)&DefaultWorkParam, (sizeof(WorkParameter) - 1) );
    	memcpy( &SysParam.WorkParam, &DefaultWorkParam, sizeof(WorkParameter) );
    	memcpy( DataBuffer, &DefaultWorkParam, sizeof(WorkParameter) );
    
    	if( NVS_WriteData( NVS_WorkParam, DataBuffer, sizeof(WorkParameter) ) != ESP_OK )
	    {
	      SysState.NVS_Fault = Fault;
	    }
    	else SysState.NVS_Fault = NoFault;
    }
    
    
   /*	应用配置信息恢复出厂值	*/
   {
		DefaultAppParam.Sum = SysCheckvalue( (uint8_t *)&DefaultAppParam, (sizeof(AppParameter) - 1) );
    	memcpy( &SysParam.AppParam, &DefaultAppParam, sizeof(AppParameter) );
    	memcpy( DataBuffer, &DefaultAppParam, sizeof(AppParameter) );
    
    	if( NVS_WriteData( NVS_AppParam, DataBuffer, sizeof(AppParameter) ) != ESP_OK )
	    {
	      SysState.NVS_Fault = Fault;
	    }
    	else SysState.NVS_Fault = NoFault;
    }
}




/**
  * @brief  保存工作模式配置信息
  * @param  none
  * @retval   - ESP_OK if value was set successfully
  *           - ESP_FAIL if there is an internal error; most likely due to corrupted
  */
static esp_err_t WorkParamSave( void )
{
	esp_err_t err;
	
	vTaskSuspendAll( );
	
	SysParam.WorkParam.Sum = SysCheckvalue( (uint8_t *)&SysParam.WorkParam, (sizeof(WorkParameter) - 1) );
	memcpy( DataBuffer, &SysParam.WorkParam, sizeof(WorkParameter) );
	
	xTaskResumeAll( );
	
	
	err = NVS_WriteData( NVS_WorkParam, DataBuffer, sizeof(WorkParameter) );
	return err;
}



/**
  * @brief  保存MODBUS RTU从机配置信息
  * @param  none
  * @retval   - ESP_OK if value was set successfully
  *           - ESP_FAIL if there is an internal error; most likely due to corrupted
  */
static esp_err_t ModbusRtuSlaveParamSave( void )
{
	esp_err_t err;
	
	vTaskSuspendAll( );
	
	SysParam.ModbusRtuSlaveParam.Sum = SysCheckvalue( (uint8_t *)&SysParam.ModbusRtuSlaveParam, (sizeof(ModbusRtuSlaveParameter) - 1) );
	memcpy( DataBuffer, &SysParam.ModbusRtuSlaveParam, sizeof(ModbusRtuSlaveParameter) );
	
	xTaskResumeAll( );
	
	err = NVS_WriteData( NVS_ModbusRtuSlaveParam, DataBuffer, sizeof(ModbusRtuSlaveParameter) );
	return err;
}



 /**
  * @brief  保存应用配置信息
  * @param  none
  * @retval   - ESP_OK if value was set successfully
  *           - ESP_FAIL if there is an internal error; most likely due to corrupted
  */
static esp_err_t AppParamSave( void )
{
	esp_err_t err;
	
	vTaskSuspendAll( );
	
	SysParam.AppParam.Sum = SysCheckvalue( (uint8_t *)&SysParam.AppParam, (sizeof(AppParameter) - 1) );
	memcpy( DataBuffer, &SysParam.AppParam, sizeof(AppParameter) );
	
	xTaskResumeAll( );
	
	err = NVS_WriteData( NVS_AppParam, DataBuffer, sizeof(AppParameter) );
	return err;
}


 
/**
	* @brief  保存参数信息
	* @param  none
	* @retval none
  */
void SysParamSave( void )
{
	EventBits_t EventBits = 0;
	
  
	/*  保存MODBUS RTU从机配置信息  */
	EventBits = xEventGroupWaitBits(SysEvent, ModbusRtuSlaveParamSaveFlag, pdTRUE, pdTRUE , 0 );
  	if( EventBits & ModbusRtuSlaveParamSaveFlag )
    {
		if( ModbusRtuSlaveParamSave( ) == ESP_OK ) SysState.NVS_Fault = NoFault;
    	else SysState.NVS_Fault = Fault;
  	}
  	
  	
  	/*  保存工作模式配置信息  */
	EventBits = xEventGroupWaitBits(SysEvent, WorkParamSaveFlag, pdTRUE, pdTRUE , 0 );
  	if( EventBits & WorkParamSaveFlag )
    {
		if( WorkParamSave( ) == ESP_OK ) SysState.NVS_Fault = NoFault;
    	else SysState.NVS_Fault = Fault;
  	}
  	
  	
  	/*  保存应用配置信息  */
	EventBits = xEventGroupWaitBits(SysEvent, AppParamSaveFlag, pdTRUE, pdTRUE , 0 );
  	if( EventBits & AppParamSaveFlag )
    {
		if( AppParamSave( ) == ESP_OK ) SysState.NVS_Fault = NoFault;
    	else SysState.NVS_Fault = Fault;
  	}
  	
  	
  	/*  恢复出厂设置  */
	EventBits = xEventGroupWaitBits(SysEvent, FactoryResetFlag, pdTRUE, pdTRUE , 0 );
  	if( EventBits & FactoryResetFlag )
    {
		FactoryReset(  );
		
		vTaskDelay( 100 / portTICK_PERIOD_MS );
		
		esp_restart( );
  	}
  } 
  
  
  
  
/**
  * @brief  系统复位处理
  * @param  none
  * @retval none
  */
void SysResetProcess( void )
{
 	EventBits_t EventBits = 0;
 	
 	EventBits = xEventGroupWaitBits(SysEvent, SysResetFlag, pdTRUE, pdTRUE , 0 );

	if( EventBits & SysResetFlag )
    {
		esp_restart( );
  	}
}
 
 
 
 /**
	* @brief  初始化系统参数
	* @param  none
	* @retval none
  	*/
static void SysParam_Init( void )
{
	esp_err_t err;
	uint8_t sum;
	gpio_config_t io_conf = {};
	
	/*  初始化恢复出厂设置按键  */
	//disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    //set as output mode
    io_conf.mode = GPIO_MODE_INPUT;
    //bit mask of the pins that you want to set
    io_conf.pin_bit_mask = (1ULL<<GPIO_NUM_4);
    //disable pull-down mode
    io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
    //disable pull-up mode
    io_conf.pull_up_en = GPIO_PULLUP_ENABLE;
    //configure GPIO with the given settings
    gpio_config(&io_conf);
    
	  
	/*  初始化系统状态变量  */
  	memset( &SysState, 0, sizeof(SysState) );
  	
  	SysState.AtpsSaParam.SensorFault = Fault;
  	SysState.AtpsSaParam.CommFault = Fault;
	SysState.AtpsSaParam.Rssi = -120;
  	
  	SysState.AtpsOaParam.SensorFault = Fault;
  	SysState.AtpsOaParam.CommFault = Fault;
	SysState.AtpsOaParam.Rssi = -120;
  	
  	SysState.AtpsRaParam.SensorFault = Fault;
  	SysState.AtpsRaParam.CommFault = Fault;
	SysState.AtpsRaParam.Rssi = -120;
  	
  	SysState.AtpsMaParam.SensorFault = Fault;
  	SysState.AtpsMaParam.CommFault = Fault;
	SysState.AtpsMaParam.Rssi = -120;
  	
  	SysState.AtpsExaParam.SensorFault = Fault;
  	SysState.AtpsExaParam.CommFault = Fault;
	SysState.AtpsExaParam.Rssi = -120;
  	
  	SysState.AtpsRoomaParam.SensorFault = Fault;
  	SysState.AtpsRoomaParam.CommFault = Fault;
	SysState.AtpsRoomaParam.Rssi = -120;
  	
  	SysState.AtpsCoolaParam.SensorFault = Fault;
  	SysState.AtpsCoolaParam.CommFault = Fault;
	SysState.AtpsCoolaParam.Rssi = -120;
  	
  	SysState.AtpsHeataParam.SensorFault = Fault;
  	SysState.AtpsHeataParam.CommFault = Fault;
	SysState.AtpsHeataParam.Rssi = -120;
  	
  	SysState.AtpsHumaParam.SensorFault = Fault;
  	SysState.AtpsHumaParam.CommFault = Fault;
	SysState.AtpsHumaParam.Rssi = -120;
  	
  	SysState.AtpsPreParam.SensorFault = Fault;
  	SysState.AtpsPreParam.CommFault = Fault;
	SysState.AtpsPreParam.Rssi = -120;
  	
  	SysState.AtpsRotParam.SensorFault = Fault;
  	SysState.AtpsRotParam.CommFault = Fault;
	SysState.AtpsRotParam.Rssi = -120;
  	
  	
  	SysState.NetConnectFlag = NoConnect;
  	

	/* 检测是否执行恢复出厂设置  */
	if( gpio_get_level(GPIO_NUM_4) == 0 )
	{
		/* 执行恢复出厂设置  */
		FactoryReset(  );
	}
	else
	{
		/*  读取保存的参数信息  */
	  	/*	读取MODBUS RTU从机配置信息	*/
	  	memset( &SysParam.ModbusRtuSlaveParam, 0, sizeof(ModbusRtuSlaveParameter) );
	  	
	  	err = NVS_ReadData( NVS_ModbusRtuSlaveParam, &SysParam.ModbusRtuSlaveParam,  sizeof(ModbusRtuSlaveParameter) );
	  	if( err == ESP_OK )
	  	{
			sum = SysCheckvalue( (uint8_t *)&SysParam.ModbusRtuSlaveParam, (sizeof(ModbusRtuSlaveParameter) - 1) );
		}
	  	
	  	if( (err != ESP_OK) || (sum != SysParam.ModbusRtuSlaveParam.Sum) )
	  	{
			DefaultModbusRtuSlaveParam.Sum = SysCheckvalue( (uint8_t *)&DefaultModbusRtuSlaveParam, (sizeof(ModbusRtuSlaveParameter) - 1) );
			memcpy( DataBuffer, &DefaultModbusRtuSlaveParam, sizeof(ModbusRtuSlaveParameter) );
	    	memcpy( &SysParam.ModbusRtuSlaveParam, &DefaultModbusRtuSlaveParam, sizeof(ModbusRtuSlaveParameter) );
	    	
	    
	    	if( NVS_WriteData( NVS_ModbusRtuSlaveParam, DataBuffer, sizeof(ModbusRtuSlaveParameter) ) != ESP_OK )
		    {
		      SysState.NVS_Fault = Fault;
		    }
	    	else SysState.NVS_Fault = NoFault;
	    	
	    	ESP_LOGW(TAG, "Read modbus rtu slave parameter err!!!\r\n");
	    	ESP_LOGW(TAG, "Use default modbus rtu slave parameter!!!\r\n");
		}
		
		
		/*	读取工作模式配置信息	*/
	  	memset( &SysParam.WorkParam, 0, sizeof(WorkParameter) );
	  	
	  	err = NVS_ReadData( NVS_WorkParam, &SysParam.WorkParam, sizeof(WorkParameter) );
	  	if( err == ESP_OK )
	  	{
			sum = SysCheckvalue( (uint8_t *)&SysParam.WorkParam, (sizeof(WorkParameter) - 1) );
		}
		
	  	if( (err != ESP_OK) || (sum != SysParam.WorkParam.Sum) )
	  	{
			DefaultWorkParam.Sum = SysCheckvalue( (uint8_t *)&DefaultWorkParam, (sizeof(WorkParameter) - 1) );
	    	memcpy( &SysParam.WorkParam, &DefaultWorkParam, sizeof(WorkParameter) );
	    	memcpy( DataBuffer, &DefaultWorkParam, sizeof(WorkParameter) );
	    
	    	if( NVS_WriteData( NVS_WorkParam, DataBuffer, sizeof(WorkParameter) ) != ESP_OK )
		    {
		      SysState.NVS_Fault = Fault;
		    }
	    	else SysState.NVS_Fault = NoFault;
	    	
	    	ESP_LOGW(TAG, "Read work parameter err!!!\r\n");
	    	ESP_LOGW(TAG, "Use default work parameter!!!\r\n");
		} 
		
		/*	读取应用配置信息	*/
	  	memset( &SysParam.AppParam, 0, sizeof(AppParameter) );
	  	
	  	err = NVS_ReadData( NVS_AppParam, &SysParam.AppParam, sizeof(AppParameter) );
	  	if( err == ESP_OK )
	  	{
			sum = SysCheckvalue( (uint8_t *)&SysParam.AppParam, (sizeof(AppParameter) - 1) );
		}
		
	  	if( (err != ESP_OK) || (sum != SysParam.AppParam.Sum) )
	  	{
			DefaultAppParam.Sum = SysCheckvalue( (uint8_t *)&DefaultAppParam, (sizeof(AppParameter) - 1) );
	    	memcpy( &SysParam.AppParam, &DefaultAppParam, sizeof(AppParameter) );
	    	memcpy( DataBuffer, &DefaultAppParam, sizeof(AppParameter) );
	    
	    	if( NVS_WriteData( NVS_AppParam, DataBuffer, sizeof(AppParameter) ) != ESP_OK )
		    {
		      SysState.NVS_Fault = Fault;
		    }
	    	else SysState.NVS_Fault = NoFault;
	    	
	    	ESP_LOGW(TAG, "Read app parameter err!!!\r\n");
	    	ESP_LOGW(TAG, "Use default app parameter!!!\r\n");
		} 
	}
  	
  	
	/*	保存系统重启次数	*/
	SysParam.AppParam.ResetCount++;
	AppParamSave( );
}



/**
  * @brief  初始化Led指示灯
  * @param  None
  * @retval None
  */
static void LedInit( void )
{
	gpio_config_t io_conf = {};
	
	
	//disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    //set as output mode
    io_conf.mode = GPIO_MODE_OUTPUT_OD;
    //bit mask of the pins that you want to set
    io_conf.pin_bit_mask = (1ULL<<GPIO_NUM_19);
    //disable pull-down mode
    io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
    //disable pull-up mode
    io_conf.pull_up_en = GPIO_PULLUP_ENABLE;
    //configure GPIO with the given settings
    gpio_config(&io_conf);
}




/**
  * @brief  控制Led指示灯
  * @param  None
  * @retval None
  */
void LedCtrl( void )
{
	uint8_t state = 0;
	static uint8_t flag = 0;
	static uint8_t count = 0;
	uint8_t DeviceType = 0;
	AtpsParameter *AtpsParam = NULL;

	DeviceType = SysParam.WorkParam.DeviceType;

	if( DeviceType == AtpsSa )
	{
		AtpsParam = &SysState.AtpsSaParam;
	} 
	else if( DeviceType == AtpsOa )
	{
		AtpsParam = &SysState.AtpsOaParam;
	} 
	else if( DeviceType == AtpsRa )
	{
		AtpsParam = &SysState.AtpsRaParam;
	} 
	else if( DeviceType == AtpsMa )
	{
		AtpsParam = &SysState.AtpsMaParam;
	} 
	else if( DeviceType == AtpsExa )
	{
		AtpsParam = &SysState.AtpsExaParam;
	} 
	else if( DeviceType == AtpsRooma )
	{
		AtpsParam = &SysState.AtpsRoomaParam;
	} 
	else if( DeviceType == AtpsCoola )
	{
		AtpsParam = &SysState.AtpsCoolaParam;
	} 
	else if( DeviceType == AtpsHeata )
	{
		AtpsParam = &SysState.AtpsHeataParam;
	} 
	else if( DeviceType == AtpsHuma )
	{
		AtpsParam = &SysState.AtpsHumaParam;
	} 
	else if( DeviceType == AtpsPre )
	{
		AtpsParam = &SysState.AtpsPreParam;
	} 
	else if( DeviceType == AtpsRot )
	{
		AtpsParam = &SysState.AtpsRotParam;
	} 

	
	if( (SysState.NVS_Fault == Fault) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsSa) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsOa) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsRa) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsMa) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsExa) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsRooma) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsCoola) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsHeata) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsHuma) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsPre) || \
		(AtpsParam->SensorFault == Fault && DeviceType == AtpsRot)  )
	{
		state = 0;
	}
	else if( ( (SysState.NetConnectFlag == NoConnect) || (AtpsParam->CommFault == Fault) ) &&
			(SysParam.WorkParam.WorkMode == WirelessSlave) )
	{
		state = 1;
	}
	else 
	{
		state = 2;
	}
	
	
	switch( state )
	{
    //硬件故障，指示灯2秒闪烁一次
		case 0:
		{
			if( flag == 0 )
			{
				count++;
				if( count >= 200 )
				{
					count = 0;
					flag = 1;
					
					gpio_set_level(GPIO_NUM_19, 0);
				}
			}
			else 
			{
				count++;
				if( count >= 200 )
				{
					count = 0;
					flag = 0;
					
					gpio_set_level(GPIO_NUM_19, 1);
				}
			}
		}
		break;
		
		//无线从机模式时，未连接网络或者通信故障，指示灯800毫秒闪烁一次
		case 1:
		{
			if( flag == 0 )
			{
				count++;
				if( count >= 80 )
				{
					count = 0;
					flag = 1;
					
					gpio_set_level(GPIO_NUM_19, 0);
				}
			}
			else 
			{
				count++;
				if( count >= 80 )
				{
					count = 0;
					flag = 0;
					
					gpio_set_level(GPIO_NUM_19, 1);
				}
			}
		}
		break;
		
		//正常，指示灯100毫秒闪烁一次
		case 2:
		{
			if( flag == 0 )
			{
				count++;
				if( count >= 10 )
				{
					count = 0;
					flag = 1;
					
					gpio_set_level(GPIO_NUM_19, 0);
				}
			}
			else 
			{
				count++;
				if( count >= 10 )
				{
					count = 0;
					flag = 0;
					
					gpio_set_level(GPIO_NUM_19, 1);
				}
			}
		}
		break;
	}
}



/**
  * @brief  获取芯片的温度
  * @param  None
  * @retval None
  */
void ReadChipTemp( void )
{
	static uint16_t time_cnt = 0;
	static uint8_t state = 0;
	temperature_sensor_config_t temp_sensor_config = TEMPERATURE_SENSOR_CONFIG_DEFAULT(-10, 80);

	switch( state )
	{
		case 0:
		{
			 // 初始化温度传感器，设置预期的温度范围为 -10~80℃
			ESP_ERROR_CHECK(temperature_sensor_install(&temp_sensor_config, &chip_temp_sensor));

			// 启用温度传感器
			ESP_ERROR_CHECK(temperature_sensor_enable(chip_temp_sensor));

			state = 1;
		}
		break;

		case 1:
		{
			time_cnt += 10;

			if( time_cnt >= 1000)		//每隔1秒，读取芯片温度
			{
				time_cnt = 0;

				ESP_ERROR_CHECK(temperature_sensor_get_celsius(chip_temp_sensor, &SysState.ChipTemp));
			}
		}
		break;
	}
}



/**
  * @brief  初始化系统功能外设
  * @param  None
  * @retval None
  */
void BSP_Init( void )
{
	LedInit( );										//初始化Led指示灯
	Sensor_GPIO_Init( );							//初始化传感器接口
	SysParam_Init( );								//初始化系统参数
	DigtalDisplay_Init(  );							//初始化数码管显示
}





 
 
 
 
 


